/*
 * Copyright (c) 2020
 * User:Palo
 * File:WebViewAbilitySlice.java
 * Date:2020/12/26
 */

package com.iceframework.hiapp.slice;

import com.iceframework.hiapp.core.utils.HiToastUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class WebViewAbilitySlice extends AbilitySlice {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        NetManager netManager = NetManager.getInstance(null);
        if (!netManager.hasDefaultNet()) {
            return;
        }
        NetHandle netHandle = netManager.getDefaultNet();

        // 可以获取网络状态的变化
        NetStatusCallback callback = new NetStatusCallback() {
            // 重写需要获取的网络状态变化的override函数
        };
        netManager.addDefaultNetStatusCallback(callback);

        // 通过openConnection来获取URLConnection
        HttpURLConnection connection = null;
        try {
            String urlString = "http://www.baidu.com/";
            URL url = new URL(urlString);

            URLConnection urlConnection = netHandle.openConnection(url, java.net.Proxy.NO_PROXY);
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }
            connection.setRequestMethod("GET");
            connection.connect();
            // 之后可进行url的其他操作
        } catch(Exception e) {
            HiToastUtils.show(this,"出错啦！！！",5000);
        } finally {
            connection.disconnect();
        }
    }
}
